<template>
  <div class="login_container">
    <div class="login_box">
      <div class="avator_box">
        <img src="../assets/logo.png" alt="" />
      </div>
      <el-form
        class="login_form"
        ref="loginFormRef"
        :rules="loginFormRules"
        :model="form"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item label="" class="btns">
          <el-button type="primary" @click="login('loginFormRef')"
            >登录</el-button
          >
          <el-button type="info" @click="resetLoginForm('loginFormRef')"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {
        username: "",
        password: "",
      },
      loginFormRules: {
        username: [
          { required: true, message: "请输入登录名称", trigger: "blur" },
          { min: 3, max: 10, message: "长度在3到10个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入登录密码", trigger: "blur" },
          { min: 6, max: 15, message: "长度在6到15个字符", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    resetLoginForm(loginFormRef) {
      this.$refs[loginFormRef].resetFields();
    },

    login(loginFormRef) {
      this.$refs[loginFormRef].validate(async (valid) => {
        if (!valid) {
          alert("输入不合法");
        }
        const { data: res } = await this.$http.post("login", this.form);
        if (res.meta.status == 200) {
          this.$message.success("登录成功");
        } else {
          this.$message.error("登录失败");
        }
        window.sessionStorage.setItem("token", res.data.token);
        this.$router.push("/home");
      });
    },
  },
};
</script>

<style scoped>
.login_container {
  height: 100vh;
  background-color: cadetblue;
}
.login_container .login_box {
  width: 450px;
  height: 300px;
  background-color: #fff;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
.login_container .login_box .avator_box {
  height: 130px;
  width: 130px;
  padding: 10px;
  border: 1px solid #eee;
  position: absolute;
  left: 50%;
  box-shadow: 0 0 10px #ddd;
  border-radius: 50%;
  transform: translate(-50%, -50%);
  background-color: #fff;
}
.login_container .login_box .avator_box img {
  height: 100%;
  width: 100%;
  border-radius: 50%;
}
.login_form {
  box-sizing: border-box;
  position: absolute;
  bottom: 0;
  width: 100%;
  padding: 0 20px;
}
.btns {
  display: flex;
  justify-content: flex-end;
}
</style>